#!/usr/bin/env python

from twisted.internet import reactor
from twisted.python import log
import subprocess, os
from scanner import walk
from scanner_db import CoreDB
    
class MediaInfo(object):
    stat_attrs = ('st_mode', 'st_ino', 'st_dev', 'st_nlink', 'st_uid', 'st_gid',
             'st_size', 'st_atime', 'st_mtime', 'st_ctime')    
    
    def __init__(self, path):
        self.file_path = path
        self.__get()
    def __get(self):
        m = self.__metadata__()
        ft = self.__ftype__()
        for attr in self.stat_attrs:
            val = getattr(m, attr, '')
            setattr(self, attr, val)
        self.ftype = ft
        
    def __metadata__(self):
        """
        Get the metadata information for the file.
        returns os.stat object,
        last modification time for the file.
        """
        info = None
        try:
            info = os.stat(self.file_path)
        except Exception as error:
            log.err(error, 'Error encountered.')
            info = None
        
        return info
    
    def __ftype__(self):
        """
        Get file type info somehow.
        """
        try:
            p = subprocess.Popen(['-b', self.file_path], executable='/usr/bin/file', 
                                 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
            ostream = p.stdout.read()
        except:
            ostream = ':Not supported for this platform'
        return ostream[ostream.find(':') + 1:].strip()
    
    def to_tuple(self):
        """
        Convert the object in to a tuple
        TODO: USE Named tuple instead of normal tuple
        """
        return (self.file_path, self.ftype) + tuple(getattr(self, x) for x in self.stat_attrs)
    
    def to_dict(self):
        """
        Return a map of all the attributes of current file.
        """
        return self.__dict__
    
    def __str__(self):
        return "<MediaInfo object for %s, %s>"%(self.file_path, self.ftype)

def main():
    search_path = ['/home/shashank/Desktop']
    file_types = ['jpg', 'kdc']
    log.startLogging(file('medialib.log', 'w'))
    with CoreDB(name='media') as db:
        for path in search_path:
            for media in walk(path, file_types):
                info = MediaInfo(media)
                print info.to_dict()
                db.add(info.to_dict())

    return 0
        
    
if __name__ == '__main__':
    main()
